package com.mrjy.common.handler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;



public class IntegerArrayTypeHandler extends BaseTypeHandler<Integer[]>{
	@Override
    public void setNonNullParameter(PreparedStatement ps, int i, Integer[] parameter, JdbcType jdbcType) throws SQLException {
        List<String> list = new ArrayList<>();
        for (Integer item : parameter) {
            list.add(String.valueOf(item));
        }
        ps.setString(i, list.toString());
    }

    @Override
    public Integer[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String str = rs.getString(columnName);
        if (rs.wasNull())
            return null;
        //将string转成Integer[]
        //return Arrays.stream(str.split(",")).mapToInt(Integer::valueOf).toArray();
        String[] split = str.split(",");
        List<Integer> list = new ArrayList<>();
        for (String s : split) {
			list.add(Integer.parseInt(s));
		}
        return  list.toArray(new Integer[]{0});
    }

    @Override
    public Integer[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String str = rs.getString(columnIndex);
        if (rs.wasNull())
            return null;
      //将string转成Integer[]
        //return Arrays.stream(str.split(",")).mapToInt(Integer::valueOf).toArray();
        String[] split = str.split(",");
        List<String> list = new ArrayList<>();
        for (String s : split) {
			list.add(s);
		}
        return  list.toArray(new Integer[]{});
    }

    @Override
    public Integer[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String str = cs.getString(columnIndex);
        if (cs.wasNull())
            return null;
      //将string转成Integer[]
        //return Arrays.stream(str.split(",")).mapToInt(Integer::valueOf).toArray();
        String[] split = str.split(",");
        List<String> list = new ArrayList<>();
        for (String s : split) {
			list.add(s);
		}
        return  list.toArray(new Integer[]{});
    }
}
